package test.reverselinkedlist;

public class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }

    class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {

            ListNode cur = head;
            int N = 0;
            while (cur != null) {
                cur = cur.next;
                N++;
            }
            int groupSize = N / k;
            ListNode newHead=head;
            for (int i = 0; i < groupSize-1; i++) {
                newHead=newHead.next;
            }
            ListNode one = head;
            ListNode two = one.next;
            ListNode third = two.next;
            ListNode nextGroupH = null;
            int nextGroupLen = groupSize * 2 - 1;
            for (int i = 0; i < k; i++) {

                nextGroupH = one;
                for (int j = 0; j < nextGroupLen; j++) {
                    if (nextGroupH != null) {
                        nextGroupH = nextGroupH.next;
                    }
                }
                for (int j = 0; j < groupSize - 1; j++) {
                    two.next = one;
                    one = two;
                    two = third;
                    third = third.next;
                }
                one = two;
                two = third;
                third = third.next;
                one = two;
                two = third;
                third = third.next;
            }
            return newHead;
        }

    }
}
